#include"comm.hpp"

int main()
{
    Log("child pid is : ",Debug) << getpid()<<endl;
    key_t k = ftok(PATH_NAME,PROJ_ID);
    if(k<0)
    {
        Log("create key failed",Error)<<"Client key : "<<k<<endl;
        exit(1);
    }
    Log("create key done",Debug)<<"Client key : "<<k<<endl;

    //获取共享内存
    int shmid = shmget(k,SHM_SIZE,0);
    if(shmid<0)
    {
        Log("create shm Error",Error)<<"Client key : "<<k<<endl;
        exit(2);
    }
    Log("create shm success",Error)<<"Client key : "<<k<<endl;
    //sleep(5);
    //挂接
    char *shmaddr = (char*)shmat(shmid,nullptr,0);
    if(shmaddr == nullptr)
    {
        Log("attach shm failed",Error)<<"Client key : "<<k<<endl;
        exit(3);
    }
    Log("attach shm success",Error)<<"Client key : "<<k<<endl;
    //sleep(20);


    //通信逻辑
    //client将共享内存看成一个char类型的buffer
    // char a = 'a';
    // for(;a<='c';a++)
    // {
    //     shmaddr[a-'a'] = a;
    //     //每次都向shmaddr起始位置写入
    //     // snprintf(shmaddr,SHM_SIZE-1,\
    //     //         "hello server,我是其他进程，我的pid：%d,inc:%c\n",getpid(),a);
    //     sleep(2);
    // }
    int fd = OpenFIFO(FIFO_NAME,WRITE);

    while (true)
    {
        ssize_t s = read(0,shmaddr,SHM_SIZE);
        if(s>0)
        {
            shmaddr[s-1] = 0;
            Signal(fd);
            if(strcmp(shmaddr,"quit") == 0) break;
        }
    }
    closeFifo(fd);

    //strcpy(shmaddr,"quit");





    //去关联
    int n = shmdt(shmaddr);
    assert(n != -1);
    Log("detach shm success",Error)<<"Client key : "<<k<<endl;
    //sleep(20);

    //client不需要删除共享内存

    return 0;
}